/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.test_finder;

import picounit.Marker;
import picounit.TestFilter;
import picounit.features.class_finder.FindAction;
import picounit.features.test_factory.TestFactory;
import picounit.features.test_instantiator.TestInstantiator;
import junit.framework.TestSuite;

class AddTestFindAction implements FindAction {
	private final ClassLoader classLoader;
	private final TestSuite testSuite;
	private final TestSuite ignoredTestSuite;
	private final IgnoreCondition isIgnored;
	private final TestFilter testFilter;
	private final TestFactory testFactory;

	private final Marker marker;

	public AddTestFindAction(TestFilter testFilter, ClassLoader classLoader,
		TestSuite testSuite, TestSuite ignoredTestSuite, Marker marker,
		TestInstantiator testInstantiator, TestFactory testFactory) {

		this.testFilter = testFilter;
		this.classLoader = classLoader;
		this.testSuite = testSuite;
		this.ignoredTestSuite = ignoredTestSuite;
		this.marker = marker;
		this.isIgnored = new IgnoreCondition(testInstantiator);
		this.testFactory = testFactory;
	}

	public void perform(String className) {
		try {
			Class<?> aClass = classLoader.loadClass(className);

			if (testFilter.matches(aClass) && marker.matches(aClass)) {
				if (!isIgnored.addToSuiteIfIgnored(aClass, ignoredTestSuite)) {
					testSuite.addTest(new SinglePicoUnitTestSuite(aClass, testFactory));
				}
			}
		}
		catch (ClassNotFoundException classNotFoundException) {
			testSuite.addTest(new ClassNotFoundFailingTest(className, classNotFoundException));
		}
	}
}